import 'package:flutter/material.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/pages/models/firmware_info_model.dart';
import 'package:inmotion_pro/pages/others/common_enum/tbox_status_type.dart';
import 'package:inmotion_pro/utils/date_format_util.dart';
import 'package:lx_widgets_library/http/base_data.dart';
import 'package:safemap/safemap.dart';

class VehicleModel extends BaseData with VehicleTypeMixin {
  final int id;
  final String sn;
  final int userId;
  final RxString nickname; // 改为 RxString
  final int type;
  final int source;
  final DateTime? createdAt;
  final DateTime? updatedAt;
  final DateTime? connectedAt;
  final String bleName;
  final String productModel;
  final Rx<TBoxStatus> tboxStatus;
  final bool hmicStatus;
  final bool realtimeLocEnabled;
  final RxnBool isOwner; //
  bool isSelected = false;
  final List<FirmwareInfoModel> firmwareInfoList; // 固件信息

  int? get createdTimeMillis {
    return createdAt?.millisecondsSinceEpoch;
  }

  int? get updatedTimeMillis {
    return updatedAt?.millisecondsSinceEpoch;
  }

  int? get connectTimeMillis {
    return connectedAt?.millisecondsSinceEpoch;
  }

  VehicleModel({
    this.id = 0,
    this.sn = "",
    this.userId = 0,
    String nickname = "", // 参数保持 String 类型
    this.type = 0,
    this.source = 0,
    this.createdAt,
    this.updatedAt,
    this.connectedAt,
    this.bleName = "",
    this.productModel = "",
    TBoxStatus tboxStatus = TBoxStatus.none,
    this.hmicStatus = false,
    this.realtimeLocEnabled = false,
    this.isSelected = false,
    this.firmwareInfoList = const [],
    bool isOwner = true, // 默认是车主，避免首页“申请车主”悬浮按钮，显示 -> 消失 出现闪烁问题
  })  : nickname = RxString(nickname),
        tboxStatus = Rx<TBoxStatus>(tboxStatus),
        isOwner = RxnBool(isOwner);

  factory VehicleModel.fromJson(Map<String, dynamic> json) {
    final safeMap = SafeMap(json);
    return VehicleModel(
      id: safeMap['id'].toInt ?? 0,
      sn: safeMap['sn'].string ?? "",
      userId: safeMap['user_id'].toInt ?? 0,
      nickname: safeMap['product_nickname'].string ??
          safeMap['vehicle_name'].string ??
          "", // 保持 String 传入
      type: safeMap['type'].toInt ?? 0,
      source: safeMap['source'].toInt ?? 0,
      createdAt: safeMap['created_at'].string != null
          ? safeMap['created_at'].dateTime
          : safeMap['created_stamp'].toInt != null
              ? DateFormatUtil.getDate(safeMap['created_stamp'].toInt!)
              : null,
      updatedAt: safeMap['updated_at'].string != null
          ? safeMap['updated_at'].dateTime
          : safeMap['updated_stamp'].toInt != null
              ? DateFormatUtil.getDate(safeMap['updated_stamp'].toInt!)
              : null,
      connectedAt: safeMap['connected_at'].string != null
          ? safeMap['connected_at'].dateTime
          : safeMap['connected_stamp'].toInt != null
              ? DateFormatUtil.getDate(safeMap['connected_stamp'].toInt!)
              : null,
      bleName:
          safeMap['device_name'].string ?? safeMap['ble_name'].string ?? "",
      productModel:
          safeMap['model'].string ?? safeMap['product_model'].string ?? "",
      tboxStatus: TBoxStatus.values.firstWhere(
          (e) => e.rawValue == safeMap['tbox_status'].toInt,
          orElse: () => TBoxStatus.none),
      hmicStatus: safeMap['hmic_status'].toInt == 1,
      realtimeLocEnabled: safeMap['realtime_loc'].toInt == 1,
      isOwner: safeMap['is_owner'].toInt == 1,
      isSelected: safeMap['is_selected'].toInt == 1,
      firmwareInfoList: safeMap['firmware_info'].list != null
          ? safeMap['firmware_info']
              .list!
              .map((e) => FirmwareInfoModel.fromMap(e as Map<String, dynamic>))
              .toList()
          : [],
    );
  }

  // 将VehicleModel对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'sn': sn,
      'user_uid': userId,
      'vehicle_name': nickname.value, // 使用 .value
      'type': type,
      'source': source,
      'created_at': createdAt?.millisecondsSinceEpoch,
      'updated_at': updatedAt?.millisecondsSinceEpoch,
      'connected_at': connectedAt?.millisecondsSinceEpoch,
      'ble_name': bleName,
      'product_model': productModel,
      'tbox_status': tboxStatus.value.rawValue,
      'hmic_status': hmicStatus ? 1 : 0,
      'realtime_loc': realtimeLocEnabled ? 1 : 0,
      'is_owner': isOwner.value == null ? null : (isOwner.value! ? 1 : 0),
      'is_selected': isSelected ? 1 : 0,
      'firmware_info':
          firmwareInfoList.map((e) => e.toMap()).toList(), // 转换为List<Map>
    };
  }

  // 获取车辆类型
  VehicleType get vehicleType {
    if (vehicleTypeMixinIsValidVehicleName(bleName: bleName)) {
      if (vehicleTypeMixinIsValidLorinVehicleName(bleName: bleName)) {
        if (vehicleTypeMixinIsV9(bleName: bleName)) {
          return VehicleType.v9;
        } else if (vehicleTypeMixinIsV12s(bleName: bleName)) {
          return VehicleType.v12s;
        } else if (vehicleTypeMixinIsRsJet(bleName: bleName)) {
          return VehicleType.rsJet;
        } else if (vehicleTypeMixinIsP6(bleName: bleName)) {
          return VehicleType.p6;
        }
      }
    }
    debugPrint(
        "❌❌❌ Unknown vehicle type for name: $bleName, productModel: $productModel");
    return VehicleType.unknown;
  }
}
